﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Newtonsoft.Json.Linq;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class BiliPage : Page
    {
        public delegate void PageChnage(BangumiType type, string sid);
        public delegate void OpenTag(string[] tag);
        public event PageChnage PageChnageEvent;
        public event OpenTag OpenTagEvent;
        public BiliPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Enabled;
            tuijian = new ObservableCollection<BanSeasonTagModel>();
            list_Home.ItemsSource = tuijian;
            SetWeekInfo();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode== NavigationMode.New)
            {
                if (tuijian.Count==0&&list_Tag.Items.Count==0)
                {
                    GetTuiJian();
                    GetTagInfo();
                    GetBangumiTimeLine();
                }
               
            }
        }
        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            //UpdateUI();
            //(sender as Button).BorderBrush = new SolidColorBrush(new Windows.UI.Color() { A=255,B=216,G=123,R=30});
            pivot.SelectedIndex =Convert.ToInt32( (sender as Button).Tag);
        }

        private void UpdateUI()
        {
            SolidColorBrush color= new SolidColorBrush(new Windows.UI.Color() { A = 0,B=0,G=0,R=0 });
            btn_Home.BorderBrush = color;
            btn_Seach.BorderBrush = color;
            btn_Tag.BorderBrush = color;
            btn_Time.BorderBrush = color;
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateUI();
            SolidColorBrush color= new SolidColorBrush(new Windows.UI.Color() { A = 255, B = 216, G = 123, R = 30 });
            switch (pivot.SelectedIndex)
            {
                case 0:
                    btn_Home.BorderBrush = color;
                    break;
                case 1:
                    btn_Tag.BorderBrush = color;
                    break;
                case 2:
                    btn_Time.BorderBrush = color;
                    break;
                case 3:
                    btn_Seach.BorderBrush = color;
                    break;
                default:
                    break;
            }
        }

        private void list_Home_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent( BangumiType.Bilibili, (e.ClickedItem as BanSeasonTagModel).season_id);
        }


        private ObservableCollection<BanSeasonTagModel> _tuijian;
        public ObservableCollection<BanSeasonTagModel> tuijian
        {
            get { return _tuijian; }
            set { _tuijian = value; NotifyPropertyChange("tuijian"); }
        }
        private int _Page = 1;
        private int _Type = 1;
        private async void GetTuiJian()
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                WebClientClass wc = new WebClientClass();
                string url = String.Format("http://bangumi.bilibili.com/api/get_season_by_tag?indexType={0}&page={1}&pagesize=40&tag_id={2}", _Type, _Page, 144);
                url +="&sign="+ BiliApiHelper.GetSign(url);
                string results = await wc.GetResults(new Uri(url));
                BanSeasonTagModel model = JsonConvert.DeserializeObject<BanSeasonTagModel>(results);
                List<BanSeasonTagModel> ls = JsonConvert.DeserializeObject<List<BanSeasonTagModel>>(model.result.ToString());
                foreach (BanSeasonTagModel item in ls)
                {
                    tuijian.Add(item);
                }
            }
            catch (Exception)
            {
                messShow.Show("读取推荐失败！", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }
        }
        //索引
        public async void GetTagInfo()
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                WebClientClass wc = new WebClientClass();
                string uri = "http://bangumi.bilibili.com/api/tags?_device=wp&_ulv=10000&appkey=422fd9d7289a1dd9&build=411005&page=" + 1 + "&pagesize=60&platform=android&ts=" + BiliApiHelper.GetTimeSpen + "000";
                string sign = BiliApiHelper.GetSign(uri);
                uri += "&sign=" + sign;
                string results = await wc.GetResults(new Uri(uri));
                JObject jo = JObject.Parse(results);
                List<TagModel> list = JsonConvert.DeserializeObject<List<TagModel>>(jo["result"].ToString());
                list_Tag.ItemsSource = list;
            }
            catch (Exception)
            {
                messShow.Show("读取索引信息失败！", 3000);

            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
                // IsLoading = false;
            }
        }
        
        int taday = 0;
        public void SetWeekInfo()
        {
            date_2.Text = DateTime.Now.AddDays(-2).Date.Month + "月" + DateTime.Now.AddDays(-2).Date.Day + "日";
            date_3.Text = DateTime.Now.AddDays(-3).Date.Month + "月" + DateTime.Now.AddDays(-3).Date.Day + "日";
            date_4.Text = DateTime.Now.AddDays(-4).Date.Month + "月" + DateTime.Now.AddDays(-4).Date.Day + "日";
            date_5.Text = DateTime.Now.AddDays(-5).Date.Month + "月" + DateTime.Now.AddDays(-5).Date.Day + "日";
            date_6.Text = DateTime.Now.AddDays(-6).Date.Month + "月" + DateTime.Now.AddDays(-6).Date.Day + "日";

            switch (DateTime.Now.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    week_0.Text = "周一";
                    week_1.Text = "周日";
                    week_2.Text = "周六";
                    week_3.Text = "周五";
                    week_4.Text = "周四";
                    week_5.Text = "周三";
                    week_5.Text = "周二";
                    taday = 1;
                    break;
                case DayOfWeek.Tuesday:
                    week_1.Text = "周一";
                    week_2.Text = "周日";
                    week_3.Text = "周六";
                    week_4.Text = "周五";
                    week_5.Text = "周四";
                    week_6.Text = "周三";
                    week_0.Text = "周二";
                    taday = 2;
                    break;
                case DayOfWeek.Wednesday:
                    week_2.Text = "周一";
                    week_3.Text = "周日";
                    week_4.Text = "周六";
                    week_5.Text = "周五";
                    week_6.Text = "周四";
                    week_0.Text = "周三";
                    week_1.Text = "周二";
                    taday = 3;
                    break;
                case DayOfWeek.Thursday:
                    week_3.Text = "周一";
                    week_4.Text = "周日";
                    week_5.Text = "周六";
                    week_6.Text = "周五";
                    week_0.Text = "周四";
                    week_1.Text = "周三";
                    week_2.Text = "周二";
                    taday = 4;
                    break;
                case DayOfWeek.Friday:
                    week_4.Text = "周一";
                    week_5.Text = "周日";
                    week_6.Text = "周六";
                    week_0.Text = "周五";
                    week_1.Text = "周四";
                    week_2.Text = "周三";
                    week_3.Text = "周二";
                    taday = 5;
                    break;
                case DayOfWeek.Saturday:
                    week_5.Text = "周一";
                    week_6.Text = "周日";
                    week_0.Text = "周六";
                    week_1.Text = "周五";
                    week_2.Text = "周四";
                    week_3.Text = "周三";
                    week_4.Text = "周二";
                    taday = 6;
                    break;
                case DayOfWeek.Sunday:
                    week_6.Text = "周一";
                    week_0.Text = "周日";
                    week_1.Text = "周六";
                    week_2.Text = "周五";
                    week_3.Text = "周四";
                    week_4.Text = "周三";
                    week_5.Text = "周二";
                    taday = 0;
                    break;
                default:
                    break;
            }
        }
        //时间表
        public async void GetBangumiTimeLine()
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                WebClientClass wc = new WebClientClass();
                string results = await wc.GetResults(new Uri("http://app.bilibili.com/bangumi/timeline_v2"));
                BangumiTimeLineModel model = new BangumiTimeLineModel();
                model = JsonConvert.DeserializeObject<BangumiTimeLineModel>(results);
                List<BangumiTimeLineModel> ban = JsonConvert.DeserializeObject<List<BangumiTimeLineModel>>(model.list.ToString());
                list_0.Items.Clear();
                list_1.Items.Clear();
                list_2.Items.Clear();
                list_3.Items.Clear();
                list_4.Items.Clear();
                list_5.Items.Clear();
                list_6.Items.Clear();
                list_7.Items.Clear();
                foreach (BangumiTimeLineModel item in ban)
                {
                    switch (item.weekday)
                    {
                        case -1:
                            list_7.Items.Add(item);
                            break;
                        case 0:
                            switch (taday)
                            {
                                case 0:
                                    list_0.Items.Add(item);
                                    break;
                                case 1:
                                    list_1.Items.Add(item);
                                    break;
                                case 2:
                                    list_2.Items.Add(item);
                                    break;
                                case 3:
                                    list_3.Items.Add(item);
                                    break;
                                case 4:
                                    list_4.Items.Add(item);
                                    break;
                                case 5:
                                    list_5.Items.Add(item);
                                    break;
                                case 6:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 1:
                            switch (taday)
                            {
                                case 1:
                                    list_0.Items.Add(item);
                                    break;
                                case 2:
                                    list_1.Items.Add(item);
                                    break;
                                case 3:
                                    list_2.Items.Add(item);
                                    break;
                                case 4:
                                    list_3.Items.Add(item);
                                    break;
                                case 5:
                                    list_4.Items.Add(item);
                                    break;
                                case 6:
                                    list_5.Items.Add(item);
                                    break;
                                case 0:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 2:
                            switch (taday)
                            {
                                case 2:
                                    list_0.Items.Add(item);
                                    break;
                                case 3:
                                    list_1.Items.Add(item);
                                    break;
                                case 4:
                                    list_2.Items.Add(item);
                                    break;
                                case 5:
                                    list_3.Items.Add(item);
                                    break;
                                case 6:
                                    list_4.Items.Add(item);
                                    break;
                                case 0:
                                    list_5.Items.Add(item);
                                    break;
                                case 1:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 3:
                            switch (taday)
                            {
                                case 3:
                                    list_0.Items.Add(item);
                                    break;
                                case 4:
                                    list_1.Items.Add(item);
                                    break;
                                case 5:
                                    list_2.Items.Add(item);
                                    break;
                                case 6:
                                    list_3.Items.Add(item);
                                    break;
                                case 0:
                                    list_4.Items.Add(item);
                                    break;
                                case 1:
                                    list_5.Items.Add(item);
                                    break;
                                case 2:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 4:
                            switch (taday)
                            {
                                case 4:
                                    list_0.Items.Add(item);
                                    break;
                                case 5:
                                    list_1.Items.Add(item);
                                    break;
                                case 6:
                                    list_2.Items.Add(item);
                                    break;
                                case 0:
                                    list_3.Items.Add(item);
                                    break;
                                case 1:
                                    list_4.Items.Add(item);
                                    break;
                                case 2:
                                    list_5.Items.Add(item);
                                    break;
                                case 3:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 5:
                            switch (taday)
                            {
                                case 5:
                                    list_0.Items.Add(item);
                                    break;
                                case 6:
                                    list_1.Items.Add(item);
                                    break;
                                case 0:
                                    list_2.Items.Add(item);
                                    break;
                                case 1:
                                    list_3.Items.Add(item);
                                    break;
                                case 2:
                                    list_4.Items.Add(item);
                                    break;
                                case 3:
                                    list_5.Items.Add(item);
                                    break;
                                case 4:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case 6:
                            switch (taday)
                            {
                                case 6:
                                    list_0.Items.Add(item);
                                    break;
                                case 0:
                                    list_1.Items.Add(item);
                                    break;
                                case 1:
                                    list_2.Items.Add(item);
                                    break;
                                case 2:
                                    list_3.Items.Add(item);
                                    break;
                                case 3:
                                    list_4.Items.Add(item);
                                    break;
                                case 4:
                                    list_5.Items.Add(item);
                                    break;
                                case 5:
                                    list_6.Items.Add(item);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                    }

                }
                
            }
            catch (Exception ex)
            {
                messShow.Show("读取番剧更新失败",3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }
        }
        //番剧时间表点击
        private void list_0_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent(BangumiType.Bilibili, (e.ClickedItem as BangumiTimeLineModel).season_id);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int i = Convert.ToInt32(this.ActualWidth / 100);
            ViewBox_num.Width = this.ActualWidth / i - 11;
        }

        private void list_Tag_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenTagEvent(new string[] { (e.ClickedItem as TagModel).tag_id.ToString(), (e.ClickedItem as TagModel).tag_name });
         
        }

        private void seach_box_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            if (seach_box.Text.Length!=0)
            {
                keyword = Uri.EscapeDataString(seach_box.Text);
                Seach_listview_Ban.Items.Clear();
                pageNum_Ban = 1;
                SeachBangumi();
              
                Ban_load_more.Visibility = Visibility.Visible;
            }
          
        }

        private void Ban_load_more_Click(object sender, RoutedEventArgs e)
        {
            SeachBangumi();
        }

        WebClientClass wc;
        private string keyword = "";
        private int pageNum_Ban = 1;
        public async void SeachBangumi()
        {
            try
            {
                Loadings = true;
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                string uri = "http://api.bilibili.com/search?_device=wp&appkey=422fd9d7289a1dd9&build=411005&keyword=" + keyword + "&main_ver=v3&page=" + pageNum_Ban + "&pagesize=20&platform=android&search_type=bangumi&source_type=0";
                string sign = BiliApiHelper.GetSign(uri);
                uri += "&sign=" + sign;
                string results = await wc.GetResults(new Uri(uri));
                SBanModel model = JsonConvert.DeserializeObject<SBanModel>(results);
                if (model.code == 0)
                {
                    List<SBanModel> ls = JsonConvert.DeserializeObject<List<SBanModel>>(model.result.ToString());
                    foreach (SBanModel item in ls)
                    {
                        Seach_listview_Ban.Items.Add(item);
                    }
                    pageNum_Ban++;
                    if (ls.Count==0||ls.Count<20)
                    {
                        Ban_load_more.Visibility = Visibility.Collapsed;
                    }
                }
                if (model.code == -3)
                {
                    messShow.Show("API Sign注册失败！请联系作者！", 3000);
                }
            }
            catch (Exception ex)
            {
                messShow.Show("搜索番剧失败" , 3000);
            }
            finally
            {
                Loadings = false;
                pr_Load.Visibility = Visibility.Collapsed;
            }

        }

        private void Seach_listview_Ban_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent( BangumiType.Bilibili, ((SBanModel)e.ClickedItem).season_id);
            //this.Frame.Navigate(typeof(BanInfoPage), ((SBanModel)e.ClickedItem).season_id);
        }
        bool Loadings = false;
        private void sc_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (sc.VerticalOffset == sc.ScrollableHeight)
            {
                if (!Loadings && Ban_load_more.Visibility==Visibility.Visible)
                {
                    Ban_load_more.IsEnabled = false;
                    Ban_load_more.Content = "正在加载";
                    SeachBangumi();
                }
            }
        }
    }


    //番剧Tag
    public class BanSeasonTagModel
    {
        public int count { get; set; }
        public int pages { get; set; }
        public object result { get; set; }

        public string bangumi_title { get; set; }//标题
        public string brief { get; set; }//简介
        public string pub_time { get; set; }//时间
        public string title { get; set; }
        public string Time
        {
            get
            {
                try
                {
                    return String.Format("{0}年{1}月", DateTime.Parse(pub_time).Year, DateTime.Parse(pub_time).Month);
                }
                catch (Exception)
                {
                    return "";
                }
                //string a = pub_time.Remove(11, pub_time.Length - 1);
            }
        }
        public string squareCover { get; set; }//封面
        public string cover { get; set; }
        public string season_id { get; set; }//SID
        public int is_finish { get; set; }//是否完结
        public string newest_ep_index { get; set; }//最新话
        public string Is_finish
        {
            get
            {
                if (is_finish == 1)
                {
                    return String.Format("已完结,共{0}话", newest_ep_index);
                }
                else
                {
                    return String.Format("更新至{0}话", newest_ep_index);
                }
            }
        }
        public int favorites { get; set; }//订阅数
        public string Favorites
        {
            get
            {
                return String.Format("{0}万人订阅", (double)favorites / 10000);
            }
        }
    }
    public class TagModel
    {
        public object result { get; set; }
        public string cover { get; set; }
        public int index { get; set; }
        public int tag_id { get; set; }
        public string tag_name { get; set; }
    }
    public class BangumiTimeLineModel
    {
        public object list { get; set; }
        public string bgmcount { get; set; }
        public string cover { get; set; }
        public string lastupdate_at { get; set; }
        public string title { get; set; }
        public string square_cover { get; set; }
        public int weekday { get; set; }
        public string spid { get; set; }
        public string season_id { get; set; }
    }
    public class SBanModel
    {
        //第一层
        public int code { get; set; }
        public int page { get; set; }//页数
        public int numResults { get; set; }//结果数量
        public int numPages { get; set; }//结果
        public object result { get; set; }//结果

        public string title { get; set; }
        public string season_id { get; set; }
        public string bangumi_id { get; set; }
        public string spid { get; set; }
        public string evaluate { get; set; }
        public string cover { get; set; }
        public int is_finish { get; set; }
        public string newest_ep_index { get; set; }
        public int total_count { get; set; }
    }

}
